// pages/resource-navigation/business-list/index.js
const MerchantAPI = require('../../../js/services/api/merchantService');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    error: '',
    searchKeyword: '',
    currentCategory: '全部',
    categories: [],
    businesses: [],
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0
    },
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { category } = options;
    if (category) {
      this.setData({
        currentCategory: decodeURIComponent(category)
      });
    }
    this.loadCategories();
    this.loadBusinesses();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreBusinesses();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '社区商家信息',
      path: '/pages/resource-navigation/business-list/index'
    };
  },

  /**
   * 加载商家分类
   */
  async loadCategories() {
    try {
      const result = await MerchantAPI.getMerchantCategories();
      if (result.success) {
        const categories = [{ category: '全部', count: 0 }];
        categories.push(...result.data);
        this.setData({ categories });
      }
    } catch (error) {
      console.error('加载商家分类失败:', error);
      // 如果API失败，使用默认分类
      this.setData({
        categories: [
          { category: '全部', count: 0 },
          { category: '便利店', count: 0 },
          { category: '蛋糕房', count: 0 },
          { category: '社区卫生站', count: 0 },
          { category: '物业报修', count: 0 },
          { category: '洗衣店', count: 0 },
          { category: '理发店', count: 0 },
          { category: '药店', count: 0 },
          { category: '银行', count: 0 }
        ]
      });
    }
  },

  /**
   * 加载商家列表
   */
  async loadBusinesses() {
    this.setData({ loading: true, error: '' });

    try {
      let result;
      if (this.data.currentCategory === '全部') {
        result = await MerchantAPI.getAllMerchants({
          page: 1,
          limit: this.data.pagination.limit
        });
      } else {
        result = await MerchantAPI.getMerchantsByCategory(this.data.currentCategory, {
          page: 1,
          limit: this.data.pagination.limit
        });
      }

      if (result.success) {
        this.setData({
          businesses: result.data.merchants,
          pagination: result.data.pagination,
          hasMore: result.data.pagination.page < result.data.pagination.totalPages,
          loading: false
        });
      } else {
        this.setData({
          error: result.message || '加载商家列表失败',
          loading: false
        });
      }
    } catch (error) {
      console.error('加载商家列表失败:', error);
      this.setData({
        error: '加载商家列表失败，请稍后重试',
        loading: false
      });
    }
  },

  /**
   * 加载更多商家
   */
  async loadMoreBusinesses() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    try {
      const nextPage = this.data.pagination.page + 1;
      let result;

      if (this.data.currentCategory === '全部') {
        result = await MerchantAPI.getAllMerchants({
          page: nextPage,
          limit: this.data.pagination.limit
        });
      } else {
        result = await MerchantAPI.getMerchantsByCategory(this.data.currentCategory, {
          page: nextPage,
          limit: this.data.pagination.limit
        });
      }

      if (result.success) {
        this.setData({
          businesses: [...this.data.businesses, ...result.data.merchants],
          pagination: result.data.pagination,
          hasMore: result.data.pagination.page < result.data.pagination.totalPages,
          loading: false
        });
      }
    } catch (error) {
      console.error('加载更多商家失败:', error);
      this.setData({ loading: false });
    }
  },

  /**
   * 刷新数据
   */
  refreshData() {
    this.setData({
      pagination: {
        ...this.data.pagination,
        page: 1
      },
      hasMore: true
    });
    this.loadBusinesses();
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  /**
   * 执行搜索
   */
  async performSearch() {
    if (!this.data.searchKeyword.trim()) {
      this.refreshData();
      return;
    }

    this.setData({
      loading: true,
      error: ''
    });

    try {
      const result = await MerchantAPI.searchMerchants(this.data.searchKeyword, {
        page: 1,
        limit: this.data.pagination.limit
      });

      if (result.success) {
        this.setData({
          businesses: result.data.merchants,
          pagination: result.data.pagination,
          hasMore: result.data.pagination.page < result.data.pagination.totalPages,
          loading: false
        });
      } else {
        this.setData({
          error: result.message || '搜索失败',
          loading: false
        });
      }
    } catch (error) {
      console.error('搜索失败:', error);
      this.setData({
        error: '搜索失败，请稍后重试',
        loading: false
      });
    }
  },

  /**
   * 切换分类
   */
  switchCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      currentCategory: category,
      searchKeyword: '',
      pagination: {
        ...this.data.pagination,
        page: 1
      },
      hasMore: true
    });
    this.loadBusinesses();
  },

  /**
   * 跳转到详情页
   */
  goToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/resource-navigation/merchant-detail/index?id=${id}`
    });
  },

  /**
   * 拨打电话
   */
  callPhone(e) {
    const { phone } = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function() {
        console.log('拨打电话成功');
      },
      fail: function(err) {
        console.error('拨打电话失败:', err);
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 导航到位置
   */
  navigateToLocation(e) {
    const { lat, lng, name } = e.currentTarget.dataset;
    if (lat && lng) {
      wx.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lng),
        name: name,
        success: function() {
          console.log('打开地图成功');
        },
        fail: function(err) {
          console.error('打开地图失败:', err);
          wx.showToast({
            title: '打开地图失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '暂无位置信息',
        icon: 'none'
      });
    }
  }
});